package com.shaobufan.museum.service.impl;

import com.shaobufan.museum.service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import static com.shaobufan.museum.contant.EmailContent.EMAIL_FAIL;
import static com.shaobufan.museum.contant.EmailContent.EMAIL_SUCCESS;

@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     *
     * @param recipientEmail 接收者的邮箱
     * @param title          邮件标题
     * @param text           邮件内容
     * @return 操作码
     */
    @Override
    public Integer sendCommonEmail(String recipientEmail, String title, String text) {
        //创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(recipientEmail);
        //邮件标题
        message.setSubject(title);
        //邮件内容
        message.setText(text);
        try {
            javaMailSender.send(message);
            return EMAIL_SUCCESS;
        } catch (MailException e) {
            return EMAIL_FAIL;
        }
    }

    @Override
    public Integer sendTemplateEmail(String recipientEmail, String title, String text) throws MessagingException {
        //创建一个MINE消息
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper mineHelper = new MimeMessageHelper(message, true);
        //谁发
        mineHelper.setFrom(from);
        //谁要接收
        mineHelper.setTo(recipientEmail);
        //邮件主题
        mineHelper.setSubject(title);
        //邮件内容   true 表示带有附件或html
        mineHelper.setText(text, true);
        try {
            javaMailSender.send(message);
            return EMAIL_SUCCESS;
        } catch (MailException e) {
            return EMAIL_FAIL;
        }
    }
}